import requests
import time
import csv

# 失败的队列
fail_list = []
# 保存的path
path = 'index_info.csv'
# 成功请求数
success = 0
# 总共请求数
total = 210


def deal_fail(list: list):
    """
    处理页面访问失败的队列
    :param list:
    :return: list
    """
    li = list
    if len(list) == 0:
        return []
    for page in list:
        if get_page(page):
            # 页面访问成功
            li.remove(page)
    return deal_fail(li)


def save_page_info(dic: dict) -> bool:
    flag = False
    each = {}
    with open(path, mode='a', encoding='utf-8', newline='') as f:
        csv_write = csv.writer(f)

        for list in dic['data']['list']:
            # 1.独家
            badge = list['badge']
            # 2.上映时间
            index_show = list['index_show']
            # 3.媒体id
            media_id = list['media_id']
            # 4.播放次数
            order = list['order']
            # 5.子标题
            subTitle = list['subTitle']
            # 6.标题
            title = list['title']
            # 7.评分
            score = list['score']
            season_id = list['season_id']
            season_status = list['season_status']
            season_type = list['season_type']
            print(badge, media_id, index_show, title, subTitle, score)
            csv_write.writerow(
                [badge, media_id, index_show, title, subTitle, score, season_id, season_status, season_type])
        flag = True
        return flag


def get_page(page: int) -> bool:
    flag = False
    url = f'https://api.bilibili.com/pgc/season/index/result?st=2&area=-1&style_id=-1&release_date=-1&season_status=-1&order=2&sort=0&page={page}&season_type=2&pagesize=20&type=1'

    header = {
        "Origin": "https://www.bilibili.com",
        "Referer": "https://www.bilibili.com",
        "Cookie":
            "buvid3=DC85195F-CB01-B663-A4AD-2BFD5F19E42329700infoc; b_nut=1698932329; i-wanna-go-back=-1; b_ut=7; _uuid=C4269EAC-29FD-CD9A-DBA4-3CA4349AD54A29832infoc; enable_web_push=DISABLE; buvid4=77D2D088-DA47-EA6C-29B4-48666F047E2531126-023110221-TYNqQZN8gC70dbC2f1aAsQ%3D%3D; DedeUserID=1845709939; DedeUserID__ckMd5=48e46ba8c3222779; rpdid=|(k|kYYJuJ~J0J'uYm)mJkJlm; header_theme_version=CLOSE; LIVE_BUVID=AUTO2316990638364095; fingerprint=b546d1292b1330e354ff23757256fd0c; buvid_fp_plain=undefined; CURRENT_QUALITY=80; home_feed_column=5; SESSDATA=4c5bffd2%2C1716375654%2C37c20%2Ab1CjBiHyrRtBoNXbQ52lhwZQMLP0HykT6OimUeThBtweaIKzo5DJP9pPzsKkg1zax-NoASVjl4SGlEVlpDcFFHNUVGcldZZjExZkNmWk4xTnJoSXEzWEJaV1Z5S1ZTX2Jya0VhWk5mNUk0T2FTdnotWDNzc2FRa2xCVThrRnVNdDZ6REU0d3RIVmV3IIEC; bili_jct=2e13811f19bfe625f2d3e46e834e2d72; browser_resolution=1536-722; buvid_fp=73650068ce8dac2752780f04e24bea5c; hit-dyn-v2=1; bili_ticket=eyJhbGciOiJIUzI1NiIsImtpZCI6InMwMyIsInR5cCI6IkpXVCJ9.eyJleHAiOjE3MDE2MDMxMDcsImlhdCI6MTcwMTM0Mzg0NywicGx0IjotMX0.j1ugTgJyqJlJQDzzZQ7SKPxjQGCi0IM9tG0Ecz-_TNs; bili_ticket_expires=1701603047; bp_video_offset_1845709939=869753176941658176; CURRENT_BLACKGAP=0; innersign=0; b_lsid=A110A810DA_18C201B9AA2; CURRENT_FNVAL=16; sid=8toqakr9; PVID=12"
    }
    resp = requests.get(url, header)
    # 设置自适应字符编码
    resp.encoding = resp.apparent_encoding
    # 将响应内容转换成字典
    dic = resp.json()  #

    # 筛选需要的数据，即返回值为code=0的请求
    if dic['code'] == 0:
        data = save_page_info(dic)
        # 保存到json文件中
        print(f"page：{page}保存成功")
        return True
    return flag


for page in range(1, total + 1):
    if get_page(page):
        # 访问成功
        success += 1
    else:
        # 添加到失败队列
        fail_list.append(page)

    time.sleep(0.5)  # 防止被禁
print(f"成功/失败：（{success}/{total-success}），总共{total}")
print("失败队列", fail_list)
# 处理失败队列
deal_fail(fail_list)
